package com.gzhryc.net_marketing.api;

import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.protocol.goods.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

public class CloudGoodsAPIService {

    private static Logger log = Logger.getLogger(CloudGoodsAPIService.class);

    private static CloudGoodsAPIService me;

    public static CloudGoodsAPIService self() {
        if(me == null) {
           me = new CloudGoodsAPIService();
        }
        return me;
    }

    private CloseableHttpClient httpClient;
    private String cloudApiHttpDomain;

    public void initial(String cloudApiHttpDomain){
        this.cloudApiHttpDomain = cloudApiHttpDomain;
        this.httpClient = HttpClients.createDefault();
    }

    /**
     * 获取云商品列表
     * @param pageNo
     * @param pageLimit
     * @return
     */
    public GoodsListResponse findGoodsList(Integer pageNo, Integer pageLimit) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/list.data").build();

            GoodsListRequest apiReq = new GoodsListRequest();
            apiReq.getBody().setPageNo(pageNo);
            apiReq.getBody().setPageLimit(pageLimit);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取商品列表信息返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    GoodsListResponse apiResp = JsonTools.fromJson(str, GoodsListResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取商品列表信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获取单个云商品信息
     * @param goodsCode
     * @return
     */
    public GoodsInfoResponse getGoodsInfo(String goodsCode) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/info.data").build();

            GoodsInfoRequest apiReq = new GoodsInfoRequest();
            apiReq.getBody().setGoodsCode(goodsCode);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取商品信息返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    GoodsInfoResponse apiResp = JsonTools.fromJson(str, GoodsInfoResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取商品信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获取云商品类型
     * @return
     */
    public GoodsTypeListResponse findGoodsTypeList() {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/type/list.data").build();

            GoodsTypeListRequest apiReq = new GoodsTypeListRequest();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取商品类型列表信息返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    GoodsTypeListResponse apiResp = JsonTools.fromJson(str, GoodsTypeListResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取商品类型列表信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 发布云商品
     * @param apiReq
     * @return
     */
    public GoodsApplyAuditResponse goodsApplyAudit(GoodsApplyAuditRequest apiReq) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/audit/apply.do").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("发布云商品返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    GoodsApplyAuditResponse apiResp = JsonTools.fromJson(str, GoodsApplyAuditResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("发布云商品错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 取消云商品发布
     * @param auditId
     * @return
     */
    public GoodsCancelAuditResponse goodsCancelAudit(Long auditId) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/audit/cancel.do").build();

            GoodsCancelAuditRequest apiReq = new GoodsCancelAuditRequest();
            apiReq.getBody().setAuditId(auditId);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("取消云商品发布返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    GoodsCancelAuditResponse apiResp = JsonTools.fromJson(str, GoodsCancelAuditResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("取消云商品发布错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 修改云商品状态
     * @param goodsCode
     * @param state
     * @return
     */
    public DefaultAPIResponse goodsUpdateState(String goodsCode, Integer state) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/state/update.do").build();

            GoodsUpdateStateRequest apiReq = new GoodsUpdateStateRequest();
            apiReq.getBody().setGoodsCode(goodsCode);
            apiReq.getBody().setState(state);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("修改云商品状态返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    DefaultAPIResponse apiResp = JsonTools.fromJson(str, DefaultAPIResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("修改云商品状态错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 云商品上架出售申请
     * @param goodsCode
     * @return
     */
    public GoodsUpSaleResponse goodsUpSale(Long projectId,String goodsCode) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/up_sale/apply.do").build();

            GoodsUpSaleRequest apiReq = new GoodsUpSaleRequest();
            apiReq.getBody().setAppId(projectId);
            apiReq.getBody().setGoodsCode(goodsCode);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("申请云商品售卖返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    GoodsUpSaleResponse apiResp = JsonTools.fromJson(str, GoodsUpSaleResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("申请云商品售卖错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
